package com.example.healthcondition.controller;

import com.example.healthcondition.services.UserServer;
import com.example.healthcondition.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserServer userServer;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        boolean isAuthenticated = userServer.validateUser(username, password);

        Map<String, Object> response = new HashMap<>();
        if (isAuthenticated) {
            Integer userId = userServer.getUserIdByUsername(username);
            String token = jwtTokenUtil.generateToken(username, userId);
            response.put("flag", true);
            response.put("message", "Login successful");
            response.put("token", token);  // 返回 Token
            return ResponseEntity.ok(response);  // 登录成功
        } else {
            response.put("flag", false);
            response.put("message", "Invalid username or password");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);  // 登录失败
        }
    }

}
